<script setup lang="ts">
import { ref, computed } from "vue";
type ToyItem = { id: number; name: string; count: number; price: number };

// Array<ToyItem> ToyItem[] 都是数组类型
const list = ref<ToyItem[]>([
  {
    id: 1,
    name: "芭比娃娃",
    count: 1,
    price: 288,
  },
  {
    id: 2,
    name: "弹弓",
    count: 5,
    price: 2,
  },
  {
    id: 3,
    name: "四驱车",
    count: 1,
    price: 5,
  },
  {
    id: 4,
    name: "陀螺",
    count: 1,
    price: 10,
  },
]);
const delToy = (id: number) => {
  if (confirm("你确认要删除我吗")) {
    list.value = list.value.filter((item) => item.id !== id);
  }
};
// 总价格
const allPrice = computed(() => {
  return list.value.reduce((preValue: number, item: ToyItem) => {
    return preValue + item.count * item.price;
  }, 0);
  // 计算的内容 => 返回的结果 我们可以直接使用
});

// 总数量
const allCount = computed(() => {
  return list.value.reduce((preValue: number, item: ToyItem) => {
    return preValue + item.count;
  }, 0);
  // 计算的内容 => 返回的结果 我们可以直接使用
});
// 添加礼物
const addToyItem = () => {
  list.value.push({
    name: "新礼物",
    id: Math.max(...list.value.map((item) => item.id)) + 1,
    price: ~~(Math.random() * 1000),
    count: ~~(Math.random() * 10),
  });
};
const userName = ref("张三");
const userNameComputed = computed({
  get() {
    return userName.value;
  },
  set(value) {
    userName.value = value;
  },
});
</script>

<template>
  <h1>小黑的礼物清单</h1>
  <button @click="addToyItem">添加礼物</button>
  <table border="2">
    <thead>
      <th>玩具名称</th>
      <th>玩具数量</th>
      <th>玩具价格</th>
      <th>操作</th>
    </thead>
    <tbody>
      <!-- 一行一行的 -->
      <tr v-for="item in list" :key="item.id">
        <td align="center" width="200">{{ item.name }}</td>
        <td align="center" width="100">{{ item.count }}</td>
        <td align="center" width="100">{{ item.price }}</td>
        <td align="center" width="100">
          <!-- @click.prevent 会停止原来的的默认事件 -->
          <a @click.prevent="delToy(item.id)">删除</a>
        </td>
      </tr>
    </tbody>
  </table>
  <p>当前总数量：{{ allCount }} 当前的总价格：{{ allPrice }}</p>
  <p>
    {{ userName }}
  </p>
  <p>
    <input type="text" v-model="userName" />
  </p>
  <p>{{ userNameComputed }}</p>
  <input type="text" v-model="userNameComputed" />
</template>

<style scoped></style>
